<?php
/**
 * Created by 张彪.
 * User: 小马出行
 * Date: 2017/12/25
 * Time: 17:05
 */
namespace app\admin\controller;

use app\admin\model\DriverAppealRecord;
use app\admin\model\RegionModel;
use my\Security;
use app\admin\logic\DriverServiceLogic;
use think\Env;
use think\Db;
use think\Validate;

class DriverService extends Base
{
    protected  $map = array();
    public function _initialize()
    {
        parent::_initialize();
        $this->map = [];
        $region_model = new RegionModel();
        $provinceList =$region_model->getRegion(['parent_id'=>1,'region_level'=>1],'region_id,region_name');
        $this->assign('provinceList',$provinceList);
    }

    //乘客物品遗失
    /*public function lost()
    {
        $config['lost_goods_type'] = get_lost_type();
        $this->assign($config);
        return view();
    }

    public function tableLost()
    {
        $page = input('get.page');
        $limit = input('get.limit');
        $driver_service_logic = new DriverServiceLogic();
        $res = $driver_service_logic->getLostList($page, $limit,$this->map,
            'driver_name,driver_phone,lost_goods_type,found_at,lost_id,is_dispose,owner_lost,handle_time');
        $count = Db::name('lost_driver_declare a')->join(['xm_driver_base'=>'b'],'b.driver_id = a.driver_id','LEFT')
            ->join(['xm_driver_info'=>'c'],'b.driver_id = c.driver_id','LEFT')
            ->where($this->map)->count();
        $res = decode_array_2($res);
        echo json_encode(array(
            'code' => 0,
            'msg' => '',
            'count' => $count,
            'data' => $res
        ));
    }

    //乘客物品遗失详情
    public function lostDetail()
    {
        $lost_id = input('get.lost_id');
        $driver_service_logic = new DriverServiceLogic();
        $info = $driver_service_logic->getLostDetailById($lost_id,'a.*,b.driver_name,c.user_name');
        if($info){
            $info = decode_array($info);
            $info['count_pic'] = count($info['goods_pic']);
            $this->assign($info);
            return view();
        }
    }

    //登记失主信息
    public function lostRegister()
    {
        $driver_service_logic = new DriverServiceLogic();
        if(IS_POST){
            $rule = array(
                'owner_lost'=>'require',
                'owner_phone' => ['regex'=>'/^1(3|4|5|7|8)\d{9}$/','require'],
            );
            $msg = array(
                'owner_lost' => '失主姓名不能为空',
                'owner_phone.require' => '失主联系方式不能为空',
                'owner_phone.regex' => '失主联系方式格式不正确',
            );
            $validate = new Validate($rule,$msg);
            if(!$validate->check(input('post.'))){
                $this->error($validate->getError(),'','',1);
            }
            $data['lost_id'] = input('post.lost_id');
            $data['owner_lost'] = input('post.owner_lost');
            $data['owner_phone'] = input('post.owner_phone');
            $data['handler_id'] = session('admin_id');
            $data['handle_time'] = time();
            $data['is_dispose'] = 1;
            $driver_service_logic->renewLost(array(),$data);
            $this->redirect(url('lostDetail',array('lost_id'=>$data['lost_id'])));
        }
        else{
            $lost_id = input('get.lost_id');
            $info = $driver_service_logic->getLostDetailById($lost_id,'a.*,b.driver_name');
            if($info['is_dispose']!=1){
                $info = decode_array($info);
                $info['count_pic'] = count($info['goods_pic']);
                $this->assign($info);
                return view();
            }
        }
    }


    //搜索乘客物品遗失信息
    public function lostSearch()
    {
        $page = input('get.page');
        $limit = input('get.limit');
        $type = input('get.type');
        $start = strtotime(input('get.start'));
        $end = strtotime(input('get.end'));
        $name = trim(input('get.driver_name'),' ');
        $phone = trim(input('get.driver_phone'),' ');
        $map = $this->map;
        switch($type){
            //发现日期
            case 1:
                if(input('get.start')){
                    $map['found_at'] = array('egt',$start);
                }
                if(input('get.end')){
                    $map['found_at'] = array('elt',$end);
                }
                if(input('get.start')&&input('get.end')){
                    $map['found_at'] = array('between',array($start,$end));
                }
                break;
            //处理时间
            case 2:
                if(input('get.start')){
                    $map['handle_time'] = array('egt',$start);
                }
                if(input('get.end')){
                    $map['handle_time'] = array('elt',$end);
                }
                if(input('get.start')&&input('get.end')){
                    $map['handle_time'] = array('between',array($start,$end));
                }
                break;
            default:break;
        }
        $category = trim(input('get.category'),' ');
        $dispose = trim(input('get.dispose'),' ');
        $category&&$map['lost_goods_type'] = $category;
        $dispose&&$map['is_dispose'] = $dispose;
        $name&&$map['b.driver_name'] = array('like',"%$name%");
        $phone&&$map['b.driver_phone'] = Security::encrypt($phone);
        $driver_service_logic = new DriverServiceLogic();
        $res = $driver_service_logic->getLostList($page, $limit,$map,
            'driver_name,driver_phone,lost_goods_type,found_at,lost_id,is_dispose,owner_lost,handle_time');
        $count = db('lost_driver_declare a')->join(['xm_driver_base'=>'b'],'b.driver_id = a.driver_id','LEFT')
            ->join(['xm_driver_info'=>'c'],'b.driver_id = c.driver_id','LEFT')->where($map)->count();
        $res = decode_array_2($res);
        echo json_encode(array(
            'code' => 0,
            'msg' => '',
            'count' => $count,
            'data' => $res
        ));

    }

    //车辆故障
    public function breakdown()
    {
        $config['breakdown_type'] = get_breakdown_type();
        $this->assign($config);
        return view();
    }

    public function tableBreakdown()
    {
        $page = input('get.page');
        $limit = input('get.limit');
        $driver_service_logic = new DriverServiceLogic();
        $res = $driver_service_logic->getBreakdownList($page, $limit,$this->map,
            'driver_name,driver_phone,car_plate,break_id,is_repaired,a.add_time,breakdown_type');
        $count = db('car_breakdown a')->join(['xm_driver_base'=>'b'],'b.driver_id = a.driver_id','LEFT')
            ->join('car_info c','c.car_id = a.car_id','LEFT')
            ->join(['xm_driver_info'=>'d'],'b.driver_id = d.driver_id','LEFT')
            ->where($this->map)->count();
        $res = decode_array_2($res);
        echo json_encode(array(
            'code' => 0,
            'msg' => '',
            'count' => $count,
            'data' => $res
        ));
    }

    //车辆故障详情
    public function breakdownDetail()
    {
        $break_id = input('get.break_id');
        $driver_service_logic = new DriverServiceLogic();
        $info = $driver_service_logic->getBreakdownDetailById($break_id,'a.*,b.driver_name,b.driver_phone,c.car_plate');
        if($info){
            $info = decode_array($info);
            $this->assign($info);
            return view();
        }
    }

    //搜索车辆故障信息
    public function breakdownSearch()
    {
        $page = input('get.page');
        $limit = input('get.limit');
        $start = strtotime(input('get.start'));
        $end = strtotime(input('get.end'));
        $name = trim(input('get.driver_name'),' ');
        $phone = trim(input('get.driver_phone'),' ');
        $map = $this->map;
        if(input('get.start')){
            $map['found_at'] = array('egt',$start);
        }
        if(input('get.end')){
            $map['found_at'] = array('elt',$end);
        }
        if(input('get.start')&&input('get.end')){
            $map['found_at'] = array('between',array($start,$end));
        }
        $category = trim(input('get.category'),' ');
        $repaired = trim(input('get.repaired'),' ');
        $category&&$map['breakdown_type'] = $category;
        $repaired&&$map['is_repaired'] = $repaired;
        $name&&$map['b.driver_name'] = array('like',"%$name%");
        $phone&&$map['b.driver_phone'] = Security::encrypt($phone);
        $driver_service_logic = new DriverServiceLogic();
        $res = $driver_service_logic->getBreakdownList($page, $limit,$map,
            'driver_name,driver_phone,car_plate,break_id,is_repaired,a.add_time,breakdown_type');
        $count = db('car_breakdown a')->join(['xm_driver_base'=>'b'],'b.driver_id = a.driver_id','LEFT')
            ->join('car_info c','c.car_id = a.car_id','LEFT')
            ->join(['xm_driver_info'=>'d'],'b.driver_id = d.driver_id','LEFT')
            ->where($map)->count();
        $res = decode_array_2($res);
        echo json_encode(array(
            'code' => 0,
            'msg' => '',
            'count' => $count,
            'data' => $res
        ));

    }

    //特殊情况报备
    public function special()
    {
        $config['breakdown_type'] = get_breakdown_type();
        $this->assign($config);
        return view();
    }

    public function tableSpecial()
    {
        $page = input('get.page');
        $limit = input('get.limit');
        $driver_service_logic = new DriverServiceLogic();
        $res = $driver_service_logic->getSpecialList($page, $limit,$this->map,
            'driver_name,driver_phone,case_id,case_detail,add_time');
        $count = db('exceptional_case a')->join(['xm_driver_base'=>'b'],'b.driver_id = a.driver_id','LEFT')
            ->join(['xm_driver_info'=>'c'],'b.driver_id = c.driver_id','LEFT')
            ->where($this->map)->count();
        $res = decode_array_2($res);
        echo json_encode(array(
            'code' => 0,
            'msg' => '',
            'count' => $count,
            'data' => $res
        ));
    }

    //特殊情况报备详情
    public function specialDetail()
    {
        $case_id = input('get.case_id');
        $driver_service_logic = new DriverServiceLogic();
        $info = $driver_service_logic->getSpecialDetailById($case_id,'a.*,b.driver_name,b.driver_phone');
        if($info){
            $info = decode_array($info);
            $this->assign($info);
            return view();
        }
    }

    //搜索特殊情况报备信息
    public function specialSearch()
    {
        $page = input('get.page');
        $limit = input('get.limit');
        $start = strtotime(input('get.start'));
        $end = strtotime(input('get.end'));
        $name = trim(input('get.driver_name'),' ');
        $phone = trim(input('get.driver_phone'),' ');
        $map = $this->map;
        if(input('get.start')){
            $map['add_time'] = array('egt',$start);
        }
        if(input('get.end')){
            $map['add_time'] = array('elt',$end);
        }
        if(input('get.start')&&input('get.end')){
            $map['add_time'] = array('between',array($start,$end));
        }
        $name&&$map['b.driver_name'] = array('like',"%$name%");
        $phone&&$map['b.driver_phone'] = Security::encrypt($phone);
        $driver_service_logic = new DriverServiceLogic();
        $res = $driver_service_logic->getSpecialList($page, $limit,$map,
            'driver_name,driver_phone,case_id,case_detail,add_time');
        $count = db('exceptional_case a')->join(['xm_driver_base'=>'b'],'b.driver_id = a.driver_id','LEFT')
            ->join(['xm_driver_info'=>'c'],'b.driver_id = c.driver_id','LEFT')
            ->where($map)->count();
        $res = decode_array_2($res);
        echo json_encode(array(
            'code' => 0,
            'msg' => '',
            'count' => $count,
            'data' => $res
        ));
    }*/

    //司机申诉列表
    public function appeal(){
        $page   = input('get.page');
        $limit  = input('get.limit');
        if ($page && $limit) {
            $data = input('get.');
            $res = DriverAppealRecord::appealList($page, $limit, $data);
            echo json_encode($res);exit;
        }
        return $this->fetch();
    }
    //异常单申诉处理
    public function look(){
        $appeal_id  = input('appeal_id');
        $appealInfo = DriverAppealRecord::lookDetail($appeal_id);
        return $this->fetch('',['appealInfo'=>$appealInfo]);
    }
    //异常申诉订单提交处理
    public function appealChange(){
        $data = input('post.');
        if($data['appeal_status'] == 2 && empty($data['fail_reason'])){
            echo ajax_error('请填写拒绝原因');die;
        }
        //查询申诉记录信息处理
        $appealInfo = Db::name('driver_appeal_record')->where(['appeal_id'=>$data['appeal_id']])->find();
        //查询流水冻结信息
        $recordInfo = Db::name('driver_wallet_record')->where(['record_id'=>$appealInfo['record_id'],'record_type'=>5])->find();
        //判断司机流水冻结金额 与 申请冻结金额进行判断验证
        if($appealInfo['appeal_price'] > $recordInfo['money']){
            echo ajax_error('异常：司机申请解冻金额 大于 司机收入流水冻结金额');die;
        }
        if($data['appeal_status'] == 1){                                                    //审核通过
            $data['fail_reason']        = '';
            if(!empty($data['penalty'])){
                $data['penalty'] = $data['penalty']*100;                                    //罚款金额
                if($data['penalty'] > $appealInfo['appeal_price']){
                    echo ajax_error('罚款金额不能大于解冻金额');die;
                }
                $data['appeal_opra']    = 2;                                                //申诉操作：罚款
                $data['fine_time']      = time();                                           //罚款时间
                $data['unfreeze_price'] = $appealInfo['appeal_price'] - $data['penalty'];   //解冻金额
            }else{
                $data['appeal_opra']    = 1;                                                //申诉操作：解除冻结
                $data['unfreeze_price'] = $appealInfo['appeal_price'];                      //解除冻结金额
                $data['penalty']        = 0;                                                //罚款金额
            }
        }elseif($data['appeal_status'] == 2){                                               //审核拒绝
            $data['penalty']            = $appealInfo['appeal_num'] == 1?0:$appealInfo['appeal_price'];//罚款金额
            $data['fine_time']          = $appealInfo['appeal_num'] == 2?time():'';
            $data['unfreeze_price']     = 0;
        }
        $data['dispose_id']             = session('admin_id');
        $data['dispose_time']           = time();
        //java接口url链接地址
        $url = Env::get('webAppeal'.ENV.'_host');
        //第一次审核 通过  调用java接口
        if(($appealInfo['appeal_num'] == 1 && $data['appeal_status'] == 1) || $appealInfo['appeal_num'] == 2){
            $parameter = 'driverId='.$appealInfo['driver_id'].'&fineMoney='.$data['penalty'].'&orderType=1&thawMoney='.$data['unfreeze_price'].'&orderId='.$appealInfo['common_id'];
            $result = https_request($url,$parameter);
            $result = json_decode(Security::decrypt($result),true);
            if($result['status'] == 200){
                DriverAppealRecord::where(['appeal_id'=>$data['appeal_id']])->update($data);
            }
        //第一次审核 拒绝  不调用java接口
        }elseif($appealInfo['appeal_num'] == 1 && $data['appeal_status'] == 2){
            DriverAppealRecord::where(['appeal_id'=>$data['appeal_id']])->update($data);
        }
        echo ajax_success('异常单处理成功');die;

        /*$data=input();
        $data['penalty']=$data['money']-$data['appeal_price']+$data['penalty'];//真实罚款金额
        $data['unfreeze_price']=$data['money']-$data['penalty'];//解冻金额
        $data['dispose_id']=session('admin_id');
        $this->validateAppeal($data);
        $appeal_id=$data['appeal_id'];
        $url = Env::get('webAppeal'.ENV.'_host');

        if (!$data['fail_reason']||$data['num']){
            if ($data['num']==2&&$data['fail_reason']){
                $data['penalty']=$data['unfreeze_price'];
                $data['unfreeze_price']=0;
                $parameter = 'driverId='.($data['driver_id']).'&fineMoney='.(($data['penalty']*100)).'&orderType='.($data['order_type']).'&thawMoney='.($data['unfreeze_price']*100).'&orderId='.($data['order_id']);
                $result=https_request($url,$parameter);
                $results=json_decode(Security::decrypt($result),true);
            }else if(!$data['fail_reason']){
                if (!$data['fail_reason']){
                    $parameter = 'driverId='.($data['driver_id']).'&fineMoney='.($data['penalty']*100).'&orderType='.($data['order_type']).'&thawMoney='.($data['unfreeze_price']*100).'&orderId='.($data['order_id']);
                }
                $result=https_request($url,$parameter);
                $results=json_decode(Security::decrypt($result),true);
            }else{
                $results['status']=200;
            }

        }else{
            $results['status']=200;
        }
        if ($results['status']==200){
        if ($appeal_id){
            unset($data['appeal_id']);
            $data['dispose_time']=time();
            $data['penalty']=$data['penalty']*100;
            $data['appeal_price']=$data['appeal_price']*100;
            $data['unfreeze_price']=$data['unfreeze_price']*100;
            if ($data['fail_reason']){
                $data['appeal_status']=2;
            }
            $result=DriverAppealRecord::where('appeal_id',$appeal_id)->update($data);
            if ($result){
                $this->success('修改成功');
            }else{
                $this->error('修改失败');
            }
        }
        }else{
            $this->error($results['msg']);
        }*/
    }
    private function validateAppeal($data){
        if ($data['penalty']<0){
            $this->error('不能填负数，不然就打赏对方了');
        }
        if($data['appeal_price']<$data['penalty']){
            $this->error('罚款金额不能大于解冻金额');
        }
        if ($data['appeal_status']==0){
            if (empty($data['fail_reason'])){
                $this->error('失败理由不能为空');
            }
        }
    }
}
